<?php
/**
 * Permission Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service;

use app\admin\model\admin\Role;
use app\exceptions\OrdinaryException;
use think\Exception;

Class Roles {

    /**
     * 首页列表
     * @param array $get 筛选条件
     * @author zx
     * @date 2019-11-12
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];
        if ( get($get, 'name') ) {
            $map[] = ['name', 'LIKE', $get['name'].'%'];
        }
        if ( get($get, 'status') === 0 || get($get, 'status') === '0' || get($get, 'status') == 1 ) {
            $map[] = ['status', '=', $get['status']];
        }
        if ( get($get, 'start_sort_num') !== NULL && get($get, 'start_sort_num') !== '' ) {
            $map[] = ['sort_num', '>=', $get['start_sort_num']];
        }
        if ( get($get, 'end_sort_num') !== NULL && get($get, 'end_sort_num') !== '' ) {
            $map[] = ['sort_num', '<=', $get['end_sort_num']];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;
        return Role::where($map)
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 状态更改
     * @author zx
     * @date 2019-11-14
     * @return \think\response
     */
    public function status(Role $roleModel)
    {
        $status = (int)(!$roleModel->status);
        $roleModel->status = $status;
        $update = $roleModel->save();
        if ( $update ) {
            return success(['status'=>$status]);
        }
        return failed('更新失败');
    }

    /**
     * 新增\编辑分组信息
     * @param array $data 数据包
     * @author zx
     * @date 2019-11-14
     * @throws OrdinaryException
     * @return boolean
     */
    public function create(array $data, string $permission_id)
    {
        try{
            app('rbac')->createRole($data, $permission_id);
        } catch ( Exception $exception ) {
            throw new OrdinaryException($exception->getMessage());
        }
        return true;
    }

    /**
     * 获取分组信息
     * @param mixed $param 条件
     * @author zx
     * @date 2019-11-15
     * @throws OrdinaryException
     * @return mixed
     */
    public function get( $param, bool $distribution=false )
    {
        try{
            $data = app('rbac')->getRole( $param, $distribution );
        } catch ( Exception $exception ) {
            throw new OrdinaryException($exception->getMessage());
        }
        return $data;
    }

    /**
     * 批量删除
     * @param mixed $data
     * @author zx
     * @date 2019-11-15
     * @throws OrdinaryException
     * @return boolean
     */
    public function destory( $data )
    {
        try{
            $bool = app('rbac')->delRole( $data );
        } catch ( Exception $exception ) {
            throw new OrdinaryException($exception->getMessage());
        }
        return $bool;
    }

}